import type { IContextMenuItem, TabDefinition } from '@nice/types'

import type { RouteLocationNormalizedGeneric } from 'vue-router'

import { computed, h, ref, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'

import { useAccessStore, useUserStore } from '#/stores'
import { Icon } from '@iconify/vue'
import { getTabKey, useTabbarStore, useTabs } from '@nice/hooks'
import { filterTree } from '@nice/utils'

export function useTabbar() {
  const router = useRouter()
  const route = useRoute()
  const accessStore = useAccessStore()
  const tabbarStore = useTabbarStore()
  const userStore = useUserStore()
  const {
    closeAllTabs,
    closeCurrentTab,
    closeLeftTabs,
    closeOtherTabs,
    closeRightTabs,
    closeTabByKey,
    getTabDisableState,
    openTabInNewWindow,
    refreshTab,
    toggleTabPin,
  } = useTabs()

  /**
   * 当前路径对应的tab的key
   */
  const currentActive = computed(() => {
    return getTabKey(route)
  })

  const currentTabs = ref<RouteLocationNormalizedGeneric[]>()
  watch([() => tabbarStore.getTabs, () => tabbarStore.updateTime], ([tabs]) => {
    currentTabs.value = tabs.map((item) => wrapperTabLocale(item))
  })

  /**
   * 初始化固定标签页
   */
  const initAffixTabs = () => {
    const affixTabs = filterTree(router.getRoutes(), (route) => {
      return !!route.meta?.affixTab
    })
    tabbarStore.setAffixTabs(affixTabs)
  }

  // 点击tab,跳转路由
  const handleClick = (key: string) => {
    const { fullPath, path } = tabbarStore.getTabByKey(key)
    router.push(fullPath || path)
  }

  // 关闭tab
  const handleClose = async (key: string) => {
    await closeTabByKey(key)
  }

  function wrapperTabLocale(tab: RouteLocationNormalizedGeneric) {
    return {
      ...tab,
      meta: {
        ...tab?.meta,
        title: tab?.meta?.title as string,
      },
    }
  }

  watch(
    () => accessStore.accessMenus,
    () => {
      initAffixTabs()
    },
    { immediate: true }
  )

  watch(
    () => route.fullPath,
    () => {
      const meta = route.matched?.[route.matched.length - 1]?.meta
      tabbarStore.addTab({
        ...route,
        meta: meta || route.meta,
      })
    },
    { immediate: true }
  )

  /**
   * 内容是否已经最大化
   * 排除 full-content模式
   */
  const contentIsMaximize = computed(() => {
    const headerIsHidden = userStore.preferences.header.hidden
    const sidebarIsHidden = userStore.preferences.sidebar.hidden
    return headerIsHidden && sidebarIsHidden && !userStore.isFullContent
  })
  const toggleMaximize = () => {
    const isMaximize = contentIsMaximize.value

    userStore.preferences.header.hidden = !isMaximize
    userStore.preferences.sidebar.hidden = !isMaximize
  }

  const createContextMenus = (tab: TabDefinition) => {
    const {
      disabledCloseAll,
      disabledCloseCurrent,
      disabledCloseLeft,
      disabledCloseOther,
      disabledCloseRight,
      disabledRefresh,
    } = getTabDisableState(tab)

    const affixTab = tab?.meta?.affixTab ?? false

    const menus: IContextMenuItem[] = [
      {
        disabled: disabledCloseCurrent,
        handler: async () => {
          await closeCurrentTab(tab)
        },
        icon: h(Icon, { icon: 'lucide:x' }),
        key: 'close',
        text: '关闭',
      },
      {
        handler: async () => {
          await toggleTabPin(tab)
        },
        icon: affixTab ? h(Icon, { icon: 'lucide:pin-off' }) : h(Icon, { icon: 'lucide:pin' }),
        key: 'affix',
        text: affixTab ? '取消固定' : '固定',
      },
      {
        handler: async () => {
          if (!contentIsMaximize.value) {
            await router.push(tab.fullPath)
          }
          toggleMaximize()
        },
        icon: contentIsMaximize.value
          ? h(Icon, { icon: 'lucide:minimize-2' })
          : h(Icon, { icon: 'lucide:fullscreen' }),
        key: contentIsMaximize.value ? 'restore-maximize' : 'maximize',
        text: contentIsMaximize.value ? '取消最大化' : '最大化',
      },
      {
        disabled: disabledRefresh,
        handler: () => refreshTab(),
        icon: h(Icon, { icon: 'lucide:rotate-cw' }),
        key: 'reload',
        text: '重新加载',
      },
      {
        handler: async () => {
          await openTabInNewWindow(tab)
        },
        icon: h(Icon, { icon: 'lucide:external-link' }),
        key: 'open-in-new-window',
        separator: true,
        text: '在新窗口打开',
      },

      {
        disabled: disabledCloseLeft,
        handler: async () => {
          await closeLeftTabs(tab)
        },
        icon: h(Icon, { icon: 'lucide:arrow-left-to-line' }),
        key: 'close-left',
        text: '关闭左侧标签页',
      },
      {
        disabled: disabledCloseRight,
        handler: async () => {
          await closeRightTabs(tab)
        },
        icon: h(Icon, { icon: 'lucide:arrow-right-to-line' }),
        key: 'close-right',
        separator: true,
        text: '关闭右侧标签页',
      },
      {
        disabled: disabledCloseOther,
        handler: async () => {
          await closeOtherTabs(tab)
        },
        icon: h(Icon, { icon: 'lucide:fold-horizontal' }),
        key: 'close-other',
        text: '关闭其他标签页',
      },
      {
        disabled: disabledCloseAll,
        handler: closeAllTabs,
        icon: h(Icon, { icon: 'lucide:arrow-right-left' }),
        key: 'close-all',
        text: '关闭全部标签页',
      },
    ]

    return menus.filter((item) => tabbarStore.getMenuList.includes(item.key))
  }

  return {
    createContextMenus,
    currentActive,
    currentTabs,
    handleClick,
    handleClose,
    toggleMaximize,
    contentIsMaximize,
  }
}
